package com.cdm.forum.controller;

import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import com.cdm.forum.config.AppConfig;
import com.cdm.forum.model.User;
import com.cdm.forum.service.impl.UserServiceImpl;
import com.cdm.forum.utils.MD5Util;
import com.cdm.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;

@Slf4j
//api说明
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private HttpSession httpSession;

    /**
     * 用户注册
     * @param username 账号
     * @param password 密码
     * @param nickname 昵称
     * @param passwordRepeat 重复密码
     * @return
     */

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password,
                           @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
//        //参数检验
//        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
//                || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(passwordRepeat)
//        ) {
//            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE );
//        }
        //参数检验
        if (!password.equals(passwordRepeat)) {
            return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtil.getUUID_32();
        //设置盐
        user.setSalt(salt);
        //生成密文
        String newPassword = MD5Util.md5Salt(password, salt);
        //设置密码
        user.setPassword(newPassword);

        //调用service层
        userService.createUser(user);
        //返回成功
        return Result.success();

    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(HttpServletRequest request,
                        @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                        @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        //参数校验
        if (user == null) {
            return Result.failed(ResultCode.FAILED_LOGIN);
        }
        //设置令牌,true是没有session时创建一个
        HttpSession session = request.getSession(true);
        //设置session的值
        session.setAttribute(AppConfig.USER_SESSION, user);
        //打印信息
        log.info("登陆成功");
        return Result.success();
    }

    //获取用户信息
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request, //required = false非必传参数
                                  @ApiParam("用户Id") @RequestParam(value = "id", required = false) Long id
    ) {

        User user = null;
        if(id == null) {
            //1. 如果id为空，从session里面获取登录信息
            HttpSession session = request.getSession(false);//没有不自动创建
            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                //用户未登录，返回错误信息
                return Result.failed(ResultCode.FAILED_FORBIDDEN );
            }
            //从session里面获取登录信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //2. 如果id不为空，从数据库查用户id信息
            user = userService.selectById(id);
        }
        //判断user是否为空
        if(user == null) {
            return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS );
        }

        //返回结果
        return Result.success(user);

    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);//没有也不能创建新的
        //判断session是否有效
        if(session != null) {
            log.info("退出成功");
            //销毁session
            session.invalidate();
        }
        return Result.success("退出成功");
    }


    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public Result<User> modify(HttpServletRequest request,
            @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
            @ApiParam("昵称") @RequestParam(value = "nickname",required = false)String nickname,
            @ApiParam("性别") @RequestParam(value = "gender",required = false)Byte gender,
            @ApiParam("邮箱") @RequestParam(value = "email",required = false)String email,
            @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false)String phoneNum,
            @ApiParam("个人简介") @RequestParam(value = "remark",required = false)String remark) {

        //1.参数检验
        if(StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(gender) && StringUtils.isEmpty(email)
                && StringUtils.isEmpty(phoneNum) && StringUtils.isEmpty(remark)) {

            return Result.failed("请输入要修改的内容");
        }

        //2.封装对象
        User updateUser = new User();

        //获取用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        updateUser.setId(user.getId());

        //设置属性
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        // 3.调用service
        userService.modifyInfo(updateUser);

        //查询最新用户
        user = userService.selectById(user.getId());

        //赋值给session
        session.setAttribute(AppConfig.USER_SESSION, user);

        return  Result.success(user);

    }

    /**
     * 修改密码
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyPwd")
    public Result modifyPwd(HttpServletRequest request,
                            @ApiParam("老密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                            @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                            @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat ){

        //1. 校验确认密码和新密码相同
        if(!newPassword.equals(passwordRepeat)) {
            return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2.获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //3. 调用service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);

        //判断session是否有效
        if(session != null) {
            log.info("退出成功");
            //销毁session
            session.invalidate();
        }

        return Result.success();
    }
}
